package org.gnomus.server.controllers;

import com.google.appengine.api.urlfetch.*;
import org.gnomus.server.Context;
import org.gnomus.server.Controller;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class Resource implements Controller {

    private static URLFetchService ufs = URLFetchServiceFactory.getURLFetchService();
    public String search;

    public boolean wikipedia() {
        assert search != null;
        Context ctx = Context.get();
        try {
            OutputStream out = ctx.res.getOutputStream();
            byte[] r = getWikipediaArticle(search);
            out.write(r);
            out.flush();
        } catch (MalformedURLException e) {
            throw new Error(e);
        } catch (IOException e) {
            throw new Error(e);
        }
        return true;
    }

    private static byte[] getWikipediaArticle(String s) {
        try {
            URL url = new URL("http://en.wikipedia.org/w/index.php?title=Special%3ASearch&search=" + s.replace(" ", "+"));
            HTTPRequest req = new HTTPRequest(url);
            req.setHeader(new HTTPHeader("User-Agent", "Educational non-profit at work. Email nikita@kuznetsovs.net for details."));
            byte[] r = ufs.fetch(req).getContent();
            Document d = Jsoup.parse(new String(r));
            Element content = d.getElementById("content");
            for (Element e : content.getElementsByClass("mw-content-ltr")) {
                String article = "<h1>" + content.getElementById("firstHeading").html() + "</h1>";
                article += e.html().replace("href=\"/", "target=\"_blank\" href=\"http://en.wikipedia.org/");
                return article.getBytes();
            }
            return content.html().getBytes();
        } catch (MalformedURLException e) {
            throw new Error(e);
        } catch (IOException e) {
            throw new Error(e);
        }

    }
}
